#第10章 日期和时间
import time
print('当前的时间戳是：%f'% time.time())
print('time.localtime()===',time.localtime())
print('time.gmtime()===',time.gmtime())
t = (2018,9,20,11,17,0,1,198,0)
print('time.mktime(t)===',time.mktime(t))
t = time.localtime()
print('time.asctime(t)===',time.asctime(t))
print('time.ctime(t)===',time.ctime())
print('time.start===',time.ctime())
time.sleep(1)
print('time.end===',time.ctime())

def producure():
    time.sleep(2)

t1 = time.clock()
producure()
print('seconds processs time:',time.clock() - t1)

t2 = time.time()
producure()
print('seconds wall time:',time.time() - t2)

t = (2016,9,25,17,50,38,6,48,0)
t= time.mktime(t)
print('time.strftime===',time.strftime('%b %d %Y %d %H:%M:%S ',time.gmtime(t)))

#打印当前时间
print(time.strftime('%Y/%m/%d %H:%M:%S'))

struct_time = time.strptime('2018/09/20 15:21:08','%Y/%m/%d %H:%M:%S')
print('returned tuple:',struct_time)

#datetime
import datetime
#today()方法
print('datetime.datetime.today() == ',datetime.datetime.today())
#now()方法
print('datetime.datetime.now() == ',datetime.datetime.now())
#utcnow()
print('datetime.datetime.utcnow() == ',datetime.datetime.utcnow())
#fromtimestamp()
print('datetime.datetime.fromtimestamp(time.time()) == ',datetime.datetime.fromtimestamp(time.time()))
#utcfromtimestamp()
print('datetime.datetime.utcfromtimestamp(time.time()) == ',datetime.datetime.utcfromtimestamp(time.time()))
#striptime()
t = datetime.datetime.now()
print('datetime.datetime.striptime() == ',datetime.datetime.strptime(str(t),'%Y-%m-%d %H:%M:%S.%f'))
#strftime()
t = datetime.datetime.now()
print('datetime.datetime.strftime() == ',datetime.datetime.strftime(t,'%Y-%m-%d %H:%M:%S'))

print('-----------------strfmat完整实例---------------------')
#一个使用strfmat()的完整实例
#! /usr/bin/python
# -*- coding:UTF-8 -*-
dt = datetime.datetime.now()
print('当前时间',dt)
print('dt.strftime(\'%Y-%m-%d %H:%M:%S.%f\') ==',dt.strftime('%Y-%m-%d %H:%M:%S.%f'))
print('dt.strftime(\'%Y-%m-%d %I:%M:%S %p\') ==',dt.strftime('%Y-%m-%d %I:%M:%S %p'))
print('dt.strftime(\'%a\') == ',dt.strftime('%a'))
print('dt.strftime(\'%A\') == ',dt.strftime('%A'))
print('dt.strftime(\'%b\') == ',dt.strftime('%b'))
print('dt.strftime(\'%B\') == ',dt.strftime('%B'))
print('dt.strftime(\'%c\') == ',dt.strftime('%c'))
print('dt.strftime(\'%x\') == ',dt.strftime('%x'))
print('dt.strftime(\'%X\') == ',dt.strftime('%X'))
print('这是一周中的第%s天' % dt.strftime('%w'))
print('这是一年中的第%s天' % dt.strftime('%j'))
print('这是一年中的第%s个星期' % dt.strftime('%U'))

#calendar
import calendar
#w,l,c分别用来指定每日宽度间隔，每星期行数，每月间隔距离
#print(calendar.calendar(2018,w=1,l=1,c=1))
#不指定w,l,c的情况下，将使用默认设置
print(calendar.calendar(2018))
print('calendar.firstweekday() == ',calendar.firstweekday())
print('calendar.isleap(2018) == ',calendar.isleap(2018))
print('calendar.leapdays(2000,2018) == ',calendar.leapdays(2000,2018))
print(calendar.month(2018,9,w=1,l=1))
print('calendar.monthcalendar(2018,9) == ',calendar.monthcalendar(2018,9))
print('calendar.monthrange(2018,9) == ',calendar.monthrange(2018,9))
print('calendar.firstweekday == ',calendar.firstweekday())
calendar.setfirstweekday(6)
print('calendar.firstweekday == ',calendar.firstweekday())

#牛刀小试 时间大杂烩
dt = datetime.datetime.now()
year = dt.strftime('%Y')
month = dt.strftime('%m')
day = dt.strftime('%d')
hnour = dt.strftime('%H')
minute = dt.strftime('%M')
second = dt.strftime('%S')
print('现在是%s年%s月%s日%s时%s分%s秒' % (year,month,day,hnour,minute,second))

print('-------------牛刀小试——时间大杂烩-----------------')
#牛刀小试——时间大杂烩
#!/usr/bin/python
#-*- coding:UTF-8 -*-

from time import strftime, localtime
from datetime import timedelta, date
import calendar

year = strftime("%Y", localtime())
mon  = strftime("%m", localtime())
day  = strftime("%d", localtime())
hour = strftime("%H", localtime())
min  = strftime("%M", localtime())
sec  = strftime("%S", localtime())

def today():
    #python中用3个引号（单引号或双引号）表示多行注释
    '''''
    get today,date format="YYYY-MM-DD"
    '''''
    return date.today()

def todaystr():
    '''
    get date string, date format="YYYYMMDD"
    '''
    return year + mon + day

def datetime():
    '''''
    get datetime,format="YYYY-MM-DD HH:MM:SS"
    '''
    return strftime("%Y-%m-%d %H:%M:%S", localtime())

def datetimestr():
    '''''
    get datetime string
    date format="YYYYMMDDHHMMSS"
    '''
    return year + mon + day + hour + min + sec


def get_day_of_day(n=0):
    '''''
    if n>=0,date is larger than today
    if n<0,date is less than today
    date format = "YYYY-MM-DD"
    '''
    if n < 0:
        n = abs(n)
        return date.today()-timedelta(days=n)
    else:
        return date.today()+timedelta(days=n)

def get_days_of_month(year, mon):
    '''''
    get days of month
    '''
    return calendar.monthrange(year, mon)[1]

def get_firstday_of_month(year, mon):
    '''''
    get the first day of month
    date format = "YYYY-MM-DD"
    '''
    days = "01"
    if int(mon) < 10:
        mon = "0" + str(int(mon))
    arr = (year, mon, days)
    return "-".join("%s" %i for i in arr)

def get_lastday_of_month(year, mon):
    '''''
    get the last day of month
    date format = "YYYY-MM-DD"
    '''
    days=calendar.monthrange(year, mon)[1]
    mon = addzero(mon)
    arr = (year, mon, days)
    return "-".join("%s" %i for i in arr)

def addzero(n):
    '''''
    add 0 before 0-9
    return 01-09
    '''
    nabs = abs(int(n))
    if nabs < 10:
        return "0" + str(nabs)
    else:
        return nabs

def get_firstday_month(n=0):
    '''''
    get the first day of month from today
    n is how many months
    '''
    (y, m, d) = getyearandmonth(n)
    d = "01"
    arr = (y, m, d)
    return "-".join("%s" %i for i in arr)

def getyearandmonth(n=0):
    '''''
    get the year,month,days from today
    befor or after n months
    '''
    thisyear = int(year)
    thismon = int(mon)
    totalmon = thismon + n
    if n >= 0:
        if totalmon <= 12:
            days = str(get_days_of_month(thisyear, totalmon))
            totalmon = addzero(totalmon)
            return year, totalmon, days
        else:
            i = totalmon//12
            j = totalmon%12
            if j == 0:
                i -= 1
                j = 12
            thisyear += i
            days = str(get_days_of_month(thisyear, j))
            j = addzero(j)
            return str(thisyear), str(j), days
    else:
        if totalmon > 0 and totalmon < 12:
            days = str(get_days_of_month(thisyear,totalmon))
            totalmon = addzero(totalmon)
            return year, totalmon, days
        else:
            i = totalmon//12
            j = totalmon%12
            if(j==0):
                i -= 1
                j = 12
            thisyear += i
            days = str(get_days_of_month(thisyear, j))
            j = addzero(j)
            return str(thisyear), str(j), days

# def get_lastday_month(n=0):
#     '''''
#     get the last day of month from today
#     n is how many months
#     '''
#     return "-".join("%s" %i for i in getyearandmonth(n))
#
# def get_today_month(n=0):
#     '''''
#     获取当前日期前后N月的日期
#     if n>0, 获取当前日期前N月的日期
#     if n<0, 获取当前日期后N月的日期
#     date format = "YYYY-MM-DD"
#     '''
#     (y, m, d) = getyearandmonth(n)
#     arr = (y, m, d)
#     if int(day) < int(d):
#         arr = (y, m, day)
#     return "-".join("%s" %i for i in arr)
#
# def get_firstday_month(n=0):
#     (y, m, d) = getyearandmonth(n)
#     arr = (y, m, '01')
#     return "-".join("%s" %i for i in arr)

def main():
    print('today is:', today())
    print('today is:', todaystr())
    print('the date time is:', datetime())
    print('data time is:', datetimestr())
    print('2 days after today is:', get_day_of_day(2))
    print('2 days before today is:', get_day_of_day(-2))
    print('get days of month:', get_days_of_month(2018,10))
    print('get_firstday_of_month:',get_firstday_of_month(2018,9))
    print('get_firstday_of_month:',get_firstday_of_month2(2018,9))
    print('get_lastday_of_month:',get_lastday_of_month(2018,9))
    print('2 months after this month is:', get_firstday_month(2))
    # print('2 months after today is:', get_today_month(2))
    # print('2 months before today is:', get_today_month(-2))
    # print('2 months before this month is:', get_firstday_month(-2))

def get_firstday_of_month2(year,month):
    day = '01'
    if int(month) < 10:
        month = '0' + str(int(month))
    attrs = (year,month,day)
    return "-".join('%s' %i for i in attrs)

if __name__=="__main__":
    main()

print('------------test-----------------')
#时间差值
print('date.today()-timedelta(days=2) == ',date.today()-timedelta(days=2))
print('timesapn == ',timedelta(days=1))
print(calendar.firstweekday())


#输入一个字符（如：lastweek），输出上周一的日期和本周一的日期和时间，
# 时间以0时0分0秒（如：2016-09-19 00:00:00 - 2016-09-26 00:00:00）
import datetime
def getMonday():
    dt = datetime.datetime.today()
    now_day = dt.strftime('%w')
    chazhi = int(now_day) - 1
    monday = datetime.date.today() - datetime.timedelta(days=chazhi)
    print('本周一是：', monday.strftime('%Y-%m-%d %H:%M:%S'))
    lastweek = monday - datetime.timedelta(days=7)
    print('上周一是：', lastweek.strftime('%Y-%m-%d %H:%M:%S'))

getMonday()
